﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace PortableVersion.Core.SourceControl.CommandLine
{
    public static class SourceControlCommandLineHelper
    {
        public static string GetCommand
            (string format, IEnumerable<KeyValuePair<SourceControlParam, string>> pars)
        {
            var rv = pars.Aggregate(format, (current, p) => current
                .Replace(String.Format("$({0})", Enum.GetName(typeof (SourceControlParam), p.Key)), p.Value));
            if (rv.Contains("$("))
            {
                throw new SourceControlException(
                    "Not all parameters are passed to the command '{0}'. We cound only generate '{1}'",
                    format, rv);
            }
            return rv;
        }

        public static IDictionary<SourceControlParam, string> GetParam(SourceControlParam pram1, string value1, SourceControlParam param2, string value2)
        {
            return new Dictionary<SourceControlParam, string>
                                                 {
                                                     {pram1, value1},
                                                     {param2, value2}
                                                 };
        }

        public static IDictionary<SourceControlParam, string> GetParam(SourceControlParam pram, string value)
        {
            return new Dictionary<SourceControlParam, string>
                                                 {
                                                     {pram, value}
                                                 };
        }

        public static bool Execute(string rootPath, string command, string args)
        {
            try
            {
                var p = new Process()
                            {
                                StartInfo = new ProcessStartInfo(command, args)
                                                {
                                                    CreateNoWindow = true,
                                                    WorkingDirectory = rootPath
                                                }
                            };
                p.Start();
                p.WaitForExit();
                return p.ExitCode == 0;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
